
export function randomStr(len = 16) {
  const random_pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'.split('');
  const out = [];
  while (len--) {
      out.push(random_pool[Math.floor(Math.random()*random_pool.length)]);
  }
  return out.join('');
}

export function randonNum(len = 3) {
  return (Math.random() * 9 + 1) * Math.pow(10, len - 1) | 0;
}

export const getTagData = (event, name) => {
  const target = event.currentTarget || event.target
  return name ? target.dataset[name] : target.dataset;
}

export const Uint8Array2HexStr = function (array, separator = '') {
 return Array.prototype.map.call(
    array,
    (bit) => bit.toString(16).padStart(2, '0')
  ).join(separator);
}

// export const bytes2long_2 = (bytes, endian) => {
//   let values = 0;
//   let i;
//   if (!endian) {
//       for(i = 7; i >= 0; --i) {
//           values <<= 8;
//           values |= (bytes[i] & 255);
//       }
//   } else {
//       for(i = 0; i < 8; ++i) {
//           values <<= 8;
//           values |= (bytes[i] & 255);
//       }
//   }
//   if (!Number.isSafeInteger(values)) {
//     console.warn(values, "超过 MAX_SAFE_INTEGER。可能存在精度丢失。");
//   }
//   return values;
// }

// export const long2Bytes_2 = (longValue, endian) =>{
//     const result = new Array(8);
//     let i;
//     let bigIntValue = BigInt(longValue)
//     if (!endian) {
//         for(i = 0; i < result.length; ++i) {
//             result[i] = bigIntValue & 255n;
//             bigIntValue = bigIntValue >> 8n;
//         }
//     } else {
//         for(i = result.length - 1; i >= 0; --i) {
//             result[i] = bigIntValue & 255n;
//             bigIntValue = bigIntValue >> 8n;
//         }
//     }
//     return result;
// }

export const long2Bytes = (longValue, littleEndian) => {
  const buffer = new ArrayBuffer(8);
  const view = new DataView(buffer);
  view.setBigUint64(0, BigInt(longValue), !!littleEndian);
  return new Uint8Array(buffer)
}

export const bytes2long = (uint8Array, littleEndian) => {
  const view = new DataView(uint8Array.buffer)
  return view.getBigUint64(0, !!littleEndian);
}

export function debounce ({resolve, timeout}) {
  let timeoutId = -1 
  return function (event) {
    timeoutId !==- 1 && clearTimeout(timeoutId)
    timeoutId = setTimeout(() => {
      resolve(event, this)
      timeoutId = -1
    }, timeout || 500)
  }
}

export function userIdParam () {
  let {userId, parentId} = wx.getStorageSync('szm_token')
  userId = parseInt(userId);
  parentId = parseInt(parentId)
  if(parentId === 0) {
    return {
      parentUserId: userId,
      childUserId: 0
    }
  } else {
    return {
      parentUserId: parentId,
      childUserId: userId
    }
  }
}
export function userIdParam2 () {
  let {userId} = wx.getStorageSync('szm_token')
  return {
    userId: parseInt(userId)
  };
}

export const int2ByteArray = int =>{
  const i8a = new Uint8Array(4)
  for (let index = 0; index < 4; index++) {
      i8a[index] = (int >> (8 * index)) & 0xFF
  }
  return i8a;
}

export const byteArray2Int = i8a => {
  return i8a.reduce((a, b, i) => a | ((b & 0xFF) << i * 8), 0)
}

export const getChecksum = i8a => {
  return i8a.reduce((a, b) => a + b) & 0xFF
}

export const addChecksum = (source) => {
  const ba = int2ByteArray(source);
  const checksum = getChecksum(ba);
  ba[3] = checksum;
  return byteArray2Int(ba)
}

/**
 * 获取dataset内容
 * @param {*} event 
 * @param {*} name 
 */
export const getDatasetData = (event, name) => {
  const target = event.currentTarget || event.target
  return name ? target.dataset[name] : target.dataset;
}

export const fnamefixed = (code) => `0x${parseInt(code).toString(16).toUpperCase().padStart(4, '0')}`

export const checkLogin = (show, url) => {
  if (!wx.getStorageSync('szm_token')) {
        !show && wx.showModal({
          title: '提示',
          content: '您未登录，请去登录',
          confirmText: "去登陆",
          confirmColor: wx.$theme.color,
          complete: (res) => {
            if(res.confirm) {
              const pgs = getCurrentPages();
              console.log(pgs);
              if (pgs[pgs.length - 1].route.indexOf('/login') === -1) {
                  wx.navigateTo({
                    url: '/pages/login/index',
                  })
              }
            }
          }
        })
        return false;
    } else {
      return true;
    }
}

export const isMobile = (m) => m && /^1[0-9]{10}$/.test(m)